package com.kmzx.one.project.config.listener;

import com.kmzx.one.project.entity.Warehouse;
import com.kmzx.one.project.events.PatchProdEvent;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.WarehouseMapper;
import com.kmzx.one.project.others.common.TwoData;
import com.kmzx.one.project.others.dso.ProdAlertDso;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component(value = "patchProdEventListener")
public class PatchProdEventListener {

    @Value("${spring.mail.username}")
    String emailUsername;

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    WarehouseMapper warehouseMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Async
    @EventListener(classes = {PatchProdEvent.class})
    @Transactional(rollbackFor = Exception.class)
    public void defaultPatchProdEvent(PatchProdEvent patchProdEvent) throws Exception {
        List<Warehouse> list = patchProdEvent.getWarehouseList();
//        for (Warehouse warehouse : list) {
//            Integer nowNumber = warehouse.getNowNumber();
//            Integer value = warehouse.getWarningValue();
//
//
//            // 当前值小于 预警值,报警
//            if (nowNumber < value) {
//            }
//        }

        List<Warehouse> endList = list.stream().filter(lt -> lt.getNowNumber() < lt.getWarningValue()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(endList)) {
            List<ProdAlertDso> alertInfo = customerMapper.findProdAlertInfo(1);
            List<String> emails = alertInfo.stream().map(uu -> uu.getEmail()).collect(Collectors.toList());
            List<String> prodIds = endList.stream().map(oo -> oo.getProductId()).collect(Collectors.toList());

            List<TwoData> prodPics = productMapper.selectProductCoverImg(prodIds);

            String subject = "商品库存补货提醒";

            if (!CollectionUtils.isEmpty(prodPics)) {
//                prodPics
                Map<String, List<TwoData>> collect = prodPics.stream().collect(Collectors.groupingBy(TwoData::getProductId));
                for (Warehouse warehouse : endList) {
                    Integer nowNumber = warehouse.getNowNumber();
                    String productName = warehouse.getProductName();
                    Integer warehouseBatch = warehouse.getWarehouseBatch();
//                String attributeWithCategoryId = warehouse.getAttributeWithCategoryId();
                    String attributeWithCategoryName = warehouse.getAttributeWithCategoryName();
                    String profiles = warehouse.getProfiles();

                    String imgUrls = collect.get(warehouse.getProductId()).get(0).getSkuId();
                    String content = prefixContent(productName, attributeWithCategoryName, profiles, warehouseBatch, nowNumber, imgUrls);

                    sendHTMLMail(subject, content, emails);

                }
            } else {
                for (Warehouse warehouse : endList) {
                    Integer nowNumber = warehouse.getNowNumber();
                    Integer warehouseBatch = warehouse.getWarehouseBatch();
                    String attributeWithCategoryName = warehouse.getAttributeWithCategoryName();
                    String productName = warehouse.getProductName();
                    String profiles = warehouse.getProfiles();

                    String content = prefixContent(productName, attributeWithCategoryName, profiles, warehouseBatch, nowNumber, "");

                    sendHTMLMail(subject, content, emails);
                }
            }

        }


    }


    public String prefixContent(String productName, String attrName, String profiles,
                                Integer batchNumber, Integer number, String imgUrl) {
        String one = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\" /><title>库存补货提醒</title><style>table,table td { padding: 1rem 2rem; border: 1px dashed #6D8DFE; border-collapse: collapse; text-align: center;}</style></head>";
        one += "<body>   快美甄选 提醒您：<br/><p style=\"text-indent: 2em;\"> 商品库存不足!!!</p><br/><br/>";
        one += "<table><tbody><tr><td>商品名称:</td>";
        one += "<td>" + productName + "</td></tr>";
        one += "<tr><td>规格-属性</td>";
        one += "<td>" + attrName + "</td></tr>";
        one += "<tr><td>货号</td>";
        one += "<td>" + profiles + "</td></tr><tr><td>当前批次</td>";
        one += "<td>第 " + batchNumber + " 批</td></tr><tr>";
        one += "<td>所剩库存</td><td> " + number + "个 </td></tr><tr><td>图文</td><td>";
        one += "<img width=\"300px\" height=\"300px\" src=\"" + imgUrl + "\"></td></tr></tbody></table></body></html>";
        return one;
    }


    public void sendHTMLMail(String subject, String content, List<String> toUser) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailUsername);
        String[] toUserArray = toUser.toArray(new String[toUser.size()]);
//        String[] toUserArray = (String[]) toUser.toArray();
        helper.setTo(toUserArray);
        helper.setSubject(subject);
        helper.setText(content, true);
        javaMailSender.send(message);
    }
}
